﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using EMC;
using System.Reflection;
using System.Threading;

namespace FileServer
{
    class FileHandler
    {
        private Socket clientSocket;
        private string downloadTo;
        private int bufferSize;
        private string[] action;
        private byte[] buffer;
        private FileManagement fileMan;

        public FileHandler(Socket clientsock, string downloadinfo)
        {
            clientSocket = clientsock;
            downloadTo = downloadinfo;
            bufferSize = 1000;
            buffer = new byte[bufferSize];

            string dbConfigFile = Path.GetDirectoryName(Assembly.GetAssembly(typeof(Program)).CodeBase) + @"/db_settings.xml";
            databaseConfiguration config = new databaseConfiguration(dbConfigFile);
            fileMan = new FileManagement(config);
        }

        public string handleFile(string[] message)
        {
            action = message;
            string ret = null;
            Dictionary<string, string> fileDictionary = convertProcotcolToDictionary(message);

            if (fileDictionary["FUNC"] == "UPLOAD")
            {
                ret = "upload data";
                data(fileDictionary);
                //fileMan.addfile(fileDictionary["NAME"], fileDictionary["DESC"], fileDictionary["USER"]);

            }
            else if (fileDictionary["FUNC"] == "DOWNLOAD")
            {
                ret = "download data";
                data(fileDictionary);
            }
            return ret;
        }



        private bool data(Dictionary<string, string> message)
        {
            
            if (message["FUNC"] == "UPLOAD")
            {
                FileStream filedata = new FileStream(downloadTo + message["NAME"], FileMode.Append, FileAccess.Write);
                //Thread.Sleep(100);
                int receivedBytesLen = 0;
                
                do

                {

                    Thread.Sleep(1);
                    System.Diagnostics.Debug.WriteLine(receivedBytesLen);
                    receivedBytesLen = clientSocket.Receive(buffer);
                    filedata.Write(buffer, 0, bufferSize);
                    
                } while (receivedBytesLen == 1000);
                System.Diagnostics.Debug.WriteLine("Completed");
                filedata.Flush();
                filedata.Close();
                
            }
            else if (message["FUNC"] == "DOWNLOAD")
            {
                FileStream filedata = new FileStream("D:\\Send\\" + message["NAME"], FileMode.Open, FileAccess.Read);

                buffer = new byte[bufferSize];
                int count;

                while ((count = filedata.Read(buffer, 0, bufferSize)) > 0)
                {
                    
                    System.Diagnostics.Debug.WriteLine(clientSocket.Send(buffer, count, SocketFlags.None));
                }

                System.Diagnostics.Debug.WriteLine("file: "+ message["NAME"]+" has been sent");
            }

            return true;
        }


        private Dictionary<string, string> convertProcotcolToDictionary(string[] message)
        {
            Dictionary<string, string> protocolMess = new Dictionary<string, string>();
            protocolMess.Add("SERVER", message[0]);
            protocolMess.Add("CAT", message[1]);
            protocolMess.Add("FUNC", message[2]);
            protocolMess.Add("NAME", message[3]);
            if (message.Length == 6)
            {
                protocolMess.Add("DESC", message[4]);
                protocolMess.Add("USER", message[5]);
            }
            
            
            

            return protocolMess;
        }

        //public void downloadfile(string filePath, string fileName)
        //{
        //    try
        //    {
        //        byte[] buffer;
        //        FileStream neofiledata = new FileStream(filePath + fileName, FileMode.Open, FileAccess.Read);

        //        buffer = new byte[bufferSize];
        //        int count;

        //        while ((count = neofiledata.Read(buffer, 0, bufferSize)) > 0)
        //        {
        //            System.Diagnostics.Debug.WriteLine("Bytes Sent: " + clientSock.Send(buffer, count, SocketFlags.None));
        //        }

        //        //System.Diagnostics.Debug.WriteLine("file: {0} has been sent", fileName);
        //    }
        //    catch (Exception err)
        //    {
        //        System.Diagnostics.Debug.WriteLine(err);
        //    }
        //}

    }
}
